<?php

/////////
//基金信息管理
////////
function guidingfund_create_page(){
	 drupal_set_title('基金信息管理');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('guidingfund_create_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function guidingfund_create_form(){	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['name'] = array(
	  '#title' => t('基金名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guidingfund_create_form']['name'])?$_SESSION['guidingfund_create_form']['name']:"",
	 );
	 
	 $form['principal_name'] = array(
	  '#title' => t('负责人名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guidingfund_create_form']['principal_name'])?$_SESSION['guidingfund_create_form']['principal_name']:"",
	 );
	 
	 $form['phone'] = array(
	  '#title' => t('联系电话'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guidingfund_create_form']['phone'])?$_SESSION['guidingfund_create_form']['phone']:"",
	 );
	 
	  $form['mail'] = array(
	  '#title' => t('联系邮箱'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guidingfund_create_form']['mail'])?$_SESSION['guidingfund_create_form']['mail']:"",
	 );
	 
	  $today = getdate();

      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('成立时间'),
	     '#default_value' => array('year' =>  $today['year'], 'month' =>  $today['mon'], 'day' => $today['mday']), 
	  );
	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['guidingfund_create_form']['remark'])?$_SESSION['guidingfund_create_form']['remark']:"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function guidingfund_create_form_validate($form, &$form_state){
	 if(!preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $form_state['values']['mail'])){
	  form_set_error('mail',t('您输入的电子邮件地址格式不正确'));
	 }
	  if (drupal_strlen($form_state['values']['name']) < 2) {
	    form_set_error('name', '您输入的基金长度太短，请确认。');
	  }
  
}

function guidingfund_create_form_submit($form, &$form_state){
	  //把表单的值存放在会话中去，由于这里涉及到了两个不同的表单之间传值。
	 $_SESSION['guidingfund_create_form'] = $form_state['values'];
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'guidingfund/create/confirm';
}

function guidingfund_confirm_page(){
  //我们为这个页面设置标题
	 drupal_set_title('提交基金信息预览');
	 
	 //这里首先作了判断，如果会话中没有设置contactus_form，返回contactus
	 if(empty($_SESSION['guidingfund_create_form'])){
	  drupal_goto('guidingfund/create');
	 }
	 $render_array = array(
	   '#markup' => '', 
	 );
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('guidingfund_confirm_form');
	 $render_array['#markup'] .= drupal_render($form);
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function guidingfund_confirm_form(){
 $form['name'] = array(
  '#title' => t('基金名称'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['guidingfund_create_form']['name'])?$_SESSION['guidingfund_create_form']['name']:"",
 );
 
 $form['principal_name'] = array(
  '#title' => t('负责人姓名'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['guidingfund_create_form']['principal_name'])?$_SESSION['guidingfund_create_form']['principal_name']:"",
 );
 
 $form['phone'] = array(
  '#title' => t('联系电话'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['guidingfund_create_form']['phone'])?$_SESSION['guidingfund_create_form']['phone']:"",
 );
 
 $form['mail'] = array(
  '#title' => t('联系邮箱'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['guidingfund_create_form']['mail'])?$_SESSION['guidingfund_create_form']['mail']:"",
 );
 $datetime = $_SESSION['guidingfund_create_form']['timestamp'];
 //表单元素“电子邮件”
 $form['timestamp'] = array(
  '#title' => t('设立时间'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['guidingfund_create_form']['timestamp'])?$datetime['year'].'年'.$datetime['month'].'月'.$datetime['day'].'日':"",
 );
 
 $form['remark'] = array(
  '#title' => t('备注'),
  '#type' => 'item',
  '#markup' => isset($_SESSION['guidingfund_create_form']['remark'])?$_SESSION['guidingfund_create_form']['remark']:"",
 );
  
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('返回'),
    '#submit' => array('guidingfund_confirm_form_back'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  
  return $form;
}

function guidingfund_confirm_form_back($form, &$form_state){
  //简单的重定向到contactus页面
 $form_state['redirect'] = 'guidingfund/create';
}

function guidingfund_confirm_form_submit($form, &$form_state){
		/**
	   * 写入数据库
	   */
	   $values = NULL;
	   //从会话中获取用户最初提交的值，并将$_SESSION['contactus_form']置为空。
	  if(empty($_SESSION['guidingfund_create_form'])){
		  //drupal_goto('contact');
		  $form_state['redirect'] = 'guidingfund/create';
	  }else{
		  $values = $_SESSION['guidingfund_create_form'];
		  unset($_SESSION['guidingfund_create_form']);
	  }
	  $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  $last_id = db_insert('guiding_fund_info')
  		->fields(array(
   			 'principal_name' => $values['principal_name'],
   			 'name' => $values['name'],
   			 'phone' => $values['phone'],
   			 'mail' => $values['mail'],
   			 'timestamp' =>  $datetime,
   			 'remark' =>  $values['remark'],
   			 'state' => 0,
  			))->execute();
	  if ($last_id!=NULL) {
	    
	    /**
	     * 执行成功了，到数据库去看看，是不是有这条记录了
	     * 显示一条信息给用户
	     */
		 $form_state['redirect'] = 'guidingfund/edit/'.$last_id;
		 	    
	  } else {
	    
	    // 数据写入失败了
	    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
	    
	  }
		
	
}

function guidingfund_list_page() {
 $html = '';
 if(user_access('edit guiding fund information')){
 	$html .= l('创建基金','guidingfund/create') . '<br />'. '<br />'; 
 
	 $html .= l('发布公告阶段','guidingfund/announce'); 
	 $header = array(
	      array('data' => '基金名称(点击编辑基金信息)'),
	      array('data' => '创建征集公告'),
	      );
	  $query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'timestamp',
	      'announce_id',
	      ))
		  ->condition('state',0,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {
		  //征集公告
		  $title = '没有发布征集公告';
		  if($node->announce_id>0){
		  	 $query = "SELECT id, title FROM " .
	           "{announce} where id = ?";
	         $queryResult = db_query($query, array($node->announce_id));
			  $ifempty = TRUE;
			 foreach ($queryResult as $announce) {
			 	 $ifempty = FALSE;
			    if($announce->id > 0)		
			 		$title = l($announce->title, 'announce/list/'.$announce->id);
			    else{
			    	if(user_access('edit guiding fund information')){
			    		$title = l('创建', 'announce/publish/'. $node->id);
					}
			    }
			 }	 
			 if($ifempty){
			 	if(user_access('edit guiding fund information')){
			    		$title = l('创建征集公告', 'announce/publish/'. $node->id);
					}
			 }
		  }  
		  else{
		  	if(user_access('edit guiding fund information')){
			    		$title = l('创建征集公告', 'announce/publish/'. $node->id);
					}
		  }
			  $rows[] = array(
		      'data' => array(
		        l($node->name, 'guidingfund/edit/'. $node->id),
		        $title,
		      )
		      );
	  }
	
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );
		  
	 $html .= l('基金申报阶段','guidingfund/guidingfund_replyset_page'); 
	 $header = array(
	      array('data' => '基金名称'),
	      array('data' => '申报材料模板'),
	      array('data' => '申报材料评审'),
	      array('data' => '进入专家评审名单'),
	      );
	  $query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'timestamp',
	      ))
		  ->condition('state',1,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {
	  	 //审批模板
	  	 $apply_template = '没有上传记录';
		 if(user_access('edit guiding fund information')){
			 $apply_template = l('上传评审材料模板','applyfile/create/'. $node->id);
		 }
		 
		  $query = "SELECT id , name FROM " .
		           "{apply_file_info} where guiding_fund_id = ? and type = ?";
		  $queryResult = db_query($query, array( $node->id, 0));
		  foreach ($queryResult as $template) {
		  if($template->id>0)
			  {  	
				$apply_template = l($template->name,'applyfile/list/'.$template->id);	
			  }
		  }
		  
			  $rows[] = array(
		      'data' => array(
		        l($node->name, 'guidingfund/edit/'. $node->id),
		        $apply_template,
		        $title = l('查看评审材料','applyfile/guidingfund/'. $node->id),
		        l('名单设置', 'guidingfund/togradedlist_perpage/'.$node->id),
		      )
		      );
	  }
	
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );
	  
	 $html .= l('专家评审阶段','guidingfund/guidingfund_expertset_page'); 
	 $header = array(
	      array('data' => '基金名称'),
	      array('data' => '专家选择'),
     	  array('data' => '评审意见查看'),
      	  array('data' => '进入尽调企业名单管理'),	     
      	   );
	  $query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'timestamp',
	      ))
		  ->condition('state',2,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {	  
			  $rows[] = array(
		      'data' => array(
		         l($node->name, 'guidingfund/edit/'. $node->id),
		         l('专家选择', 'expertmanage/choose/'.$node->id),
	      		 l('评审意见详情', 'expertmanage/all_graded_fund_view/'. $node->id),
	       		 l('进入尽调名单管理', 'guidingfund/toinvelist_page/'.$node->id),
		      )
		      );
	  }
	
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );
	
	 $html .= l('尽职调查阶段','guidingfund/guidingfund_investigationset_page'); 
	 $header = array(
	      array('data' => '基金名称'),
     	  array('data' => '尽职调查机构选择'),
      	  array('data' => '尽调模板及结果材料'),   
      	   );
	  $query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'timestamp',
	      ))
		  ->condition('state',3,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {	  
			  $rows[] = array(
		      'data' => array(
		         l($node->name, 'guidingfund/edit/'. $node->id),
		         l('尽调机构选择', 'investigatedepartment/choose/'.$node->id),
	             l('尽调材料详情', 'investigate_file/guidingfund/'.$node->id),		 
		      )
		      );
	  }
	
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );
		  
	 $html .= l('理事会决策阶段','lishihuijuece/list'); 
	 $header = array(
	      array('data' => '基金名称'),
     	  array('data' => '汇报文件管理'),
	      array('data' => '理事会决策管理'),
	      array('data' => '进入合作谈判名单设置'), 
      	   );
	  $query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'timestamp',
	      ))
		  ->condition('state',4,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {	  
			  $rows[] = array(
		      'data' => array(
		        l($node->name, 'guidingfund/edit/'. $node->id),
			    l('汇报文件管理', 'huibao_file/fundlist/'.$node->id),
		        l('理事会决策管理', 'lishihuijuece_file/fundlist/'.$node->id),
		        l('名单管理', 'guidingfund/totanpanlist_page/'.$node->id),	 
		      )
		      );
	  }
	
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );
	  
	 $html .= l('合作谈判阶段','hezuotanpan/list'); 
	 $header = array(
	      array('data' => '基金名称'),
     	  array('data' => '谈判要点对比'),
	      array('data' => '过程文件储存与备忘'),
	      array('data' => '提交过会企业名单'), 
      	   );
	  $query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'timestamp',
	      ))
		  ->condition('state',5,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {	  
			  $rows[] = array(
		      'data' => array(
		        l($node->name, 'guidingfund/edit/'. $node->id),
			    l('谈判要点对比', 'tanpanyaodian_file/list'),
		        l('过程文件储存与备忘', 'guochengwenjian_file/list'),
		        l('名单管理', 'guidingfund/finallist_page/'.$node->id),	 
		      )
		      );
	  }
	
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );
	  
	 $html .= l('发布过会企业公示阶段','guidingfund/enterprise_announce_page'); 
	 $header = array(
	      array('data' => '基金名称'),
     	  array('data' => '过会企业公示'),
      	   );
	  $query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'timestamp',
	      'enterprise_announce_id',
	      ))
		  ->condition('state',6,'=');
	  $results = $query
	      ->execute();
	  
	  $rows = array();
	  foreach ($results as $node) {
	  	//过会企业公示
	      $enterprise_announce_title = '没有发布过会企业公示';
		  if($node->enterprise_announce_id>0){
		  	 $query = "SELECT id,title FROM " .
	           "{enterprise_announce} where id = ?";
	         $queryResult = db_query($query, array($node->enterprise_announce_id));
			  $ifempty = TRUE;
			 foreach ($queryResult as $announce) {
			 	 $ifempty = FALSE;
			    if($announce->id > 0)		
			 		$enterprise_announce_title = l($announce->title, 'enterprise_announce/list/'.$announce->id);
			    else{
			    	if(user_access('edit guiding fund information')){
			    		$enterprise_announce_title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
					}
			    }
			 }	 
			 if($ifempty){
			 	if(user_access('edit guiding fund information')){
			    		$enterprise_announce_title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
					}
			 }
		  }  
		  else{
		  	if(user_access('edit guiding fund information')){
			    		$enterprise_announce_title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
					}
		  }	  
			  $rows[] = array(
		      'data' => array(
		        l($node->name, 'guidingfund/edit/'. $node->id),
			    $enterprise_announce_title,	 
		      )
		      );
	  }
	
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );
	
   }
   else{
		$header = array(
	      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
	      array('data' => '征集公告', 'field' => 'announce_id'),
	      array('data' => '过会企业公示', 'field' => 'enterprise_announce_id'),
	      );
	  $query = db_select('guiding_fund_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(15)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'timestamp',
	      'announce_id',
	      'enterprise_announce_id',
	      ));
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {
		  //征集公告
		  $title = '没有发布征集公告';
		  if($node->announce_id>0){
		  	 $query = "SELECT id, title FROM " .
	           "{announce} where id = ?";
	         $queryResult = db_query($query, array($node->announce_id));
			  $ifempty = TRUE;
			 foreach ($queryResult as $announce) {
			 	 $ifempty = FALSE;
			    if($announce->id > 0)		
			 		$title = l($announce->title, 'announce/list/'.$announce->id);
			    else{
			    	if(user_access('edit guiding fund information')){
			    		$title = l('创建征集公告', 'announce/publish/'. $node->id);
					}
			    }
			 }	 
			 if($ifempty){
			 	if(user_access('edit guiding fund information')){
			    		$title = l('创建征集公告', 'announce/publish/'. $node->id);
					}
			 }
		  }  
		  else{
		  	if(user_access('edit guiding fund information')){
			    		$title = l('创建征集公告', 'announce/publish/'. $node->id);
					}
		  }
		  
	      //过会企业公示
	      $enterprise_announce_title = '没有发布过会企业公示';
		  if($node->enterprise_announce_id>0){
		  	 $query = "SELECT id,title FROM " .
	           "{enterprise_announce} where id = ?";
	         $queryResult = db_query($query, array($node->enterprise_announce_id));
			  $ifempty = TRUE;
			 foreach ($queryResult as $announce) {
			 	 $ifempty = FALSE;
			    if($announce->id > 0)		
			 		$enterprise_announce_title = l($announce->title, 'enterprise_announce/list/'.$announce->id);
			    else{
			    	if(user_access('edit guiding fund information')){
			    		$enterprise_announce_title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
					}
			    }
			 }	 
			 if($ifempty){
			 	if(user_access('edit guiding fund information')){
			    		$enterprise_announce_title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
					}
			 }
		  }  
		  else{
		  	if(user_access('edit guiding fund information')){
			    		$enterprise_announce_title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
					}
		  }
			  $rows[] = array(
		      'data' => array(
		        l($node->name, 'guidingfund/list/'. $node->id),
		        $title,
		        $enterprise_announce_title,
		      )
		      );
	  }
	
	  $html .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
	      )
	      );
	  $html .= theme('pager',
	      array(
	            'tags' => array()
	      )
	      );
 }
  return ($html); 
}

function guidingfund_announce_page() {
 $html = '';
 if(user_access('edit guiding fund information')){
 	$html .= l('创建基金','guidingfund/create') . '<br />'. '<br />'; 
 }
 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '征集公告', 'field' => 'announce_id'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      'announce_id',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  	
	  $title = '没有发布征集公告';
	  if($node->announce_id>0){
	  	 $query = "SELECT title FROM " .
           "{announce} where id = ?";
         $queryResult = db_query($query, array($node->announce_id));
		  $ifempty = TRUE;
		 foreach ($queryResult as $announce) {
		 	 $ifempty = FALSE;
		    if($node->announce_id > 0)		
		 		$title = l($announce->title, 'announce/list/'.$node->announce_id);
		    else{
		    	if(user_access('edit guiding fund information')){
		    					  	$title = l('创建征集公告', 'announce/publish/'. $node->id);
				}
		    }
		 }	 
		 if($ifempty){
		 	if(user_access('edit guiding fund information')){
		    					  	$title = l('创建征集公告', 'announce/publish/'. $node->id);
				}
		 }
	  }  
	  else{
	  	if(user_access('edit guiding fund information')){
		    					  	$title = l('创建征集公告', 'announce/publish/'. $node->id);
				}
	  }
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function guidingfund_applyset_page() {
 $html = '';
 if(user_access('edit guiding fund information')){
 	 $html .= l('创建基金','guidingfund/create') . '<br />'. '<br />'; 
 }
 if(user_access('edit guiding fund information')){   
    $header = array(
      array('data' => '基金名称', 'field' => 'name'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '申报条件设置', 'field' => 'announce_id'),
      //array('data' => '允许提交申报材料名单管理', 'field' => 'allow_apply_set'),
      );
 }
 else{   
    $header = array(
      array('data' => '基金名称', 'field' => 'name'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '申报条件设置', 'field' => 'announce_id'),
      );
 }
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'phone',
      'mail',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  
	 $title = '没有上传记录';
	 if(user_access('edit guiding fund information')){
		 $title = l('上传评审材料模板','applyfile/create/'. $node->id);
	 }
	 
	  $query = "SELECT id , name FROM " .
	           "{apply_file_info} where guiding_fund_id = ? and type = ?";
	  $queryResult = db_query($query, array( $node->id, 0));
	  foreach ($queryResult as $template) {
	  if($template->id>0)
		  {  	
			$title = l($template->name,'applyfile/list/'.$template->id);	
		  }
	  }
	  if(user_access('edit guiding fund information')){
	  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      //  l('名单设置', 'guidingfund/allow_apply_page/'.$node->id),
	      )
	      );
	  }
	  else {
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      )
	      );
	  }
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function guidingfund_allow_apply_page($fund_id) {
  drupal_set_title('允许申请企业名单管理');
  $page_content = '';
  $page_content .= l('返回基金列表','guidingfund/guidingfund_applyset_page') . '<br />'. '<br />';
   $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$page_content .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $render_array = array(
  		'#markup' => $page_content,
  );
  $form = drupal_get_form('guidingfund_allow_apply_form', $fund_id);
  $render_array['#markup'] .= drupal_render($form ); 
  
  return $render_array; 
}

function guidingfund_allow_apply_form($form, &$form_state, $perid){
  $query = "SELECT allow_apply_list FROM " .
           "{guiding_fund_info} where id = ?";
  $company_list = db_query($query, array($perid));	
  $companys = array();
  foreach ($company_list as $company) {
      $companys = explode(',',$company->allow_apply_list);
  }
  $query = "SELECT id ,gsmc,user_id FROM " .
           "{rukurongzi} ";
  $queryResult = db_query($query);	
  
  $header = array(
    'gsmc' => t('公司名称'),
    'state' => t('详情'),
    'choose' => t('提交专家评审(空表示未进入)'),
  );
  $options = array();
  foreach ($queryResult as $node) {
  	$state = '';
  	if(in_array($node->user_id,$companys, TRUE)&&$companys!=NULL){
  		$state=  '已选择';
  	}
    $options[$node->user_id] =array(
      'gsmc' =>  l($node->gsmc, 'enterprise_information/view/'. $node->id),
      'state' => l('详情', 'enterprise_information/view/'. $node->id),
      'choose' => $state,   
    );
  }
  $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('没有公司记录'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  return $form;  
}

function guidingfund_allow_apply_form_submit($form, &$form_state){
	 $values = NULL;
	 $values = $form_state['values'];		
	 $company_list = '';
	 foreach ($values['table'] as $rows) {
         $company_list.=$rows.',';
     }
	  db_update('guiding_fund_info')
  		->fields(array(
   			 'allow_apply_list' => $company_list,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'guidingfund/allow_apply_page/'.$values['bid'];	
	 
}

function guidingfund_replyset_page() {
 $html = '';
 global $user;
 if(user_access('edit guiding fund information')){
 	$html .= l('创建基金','guidingfund/create') . '<br />'. '<br />'; 
	$header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '申报材料审查'),
      array('data' => '提交进入专家评审名单'),
      );
 }

 else{	  
 	 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '申报材料审查', 'field' => 'set'),
      );
 }

	  
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'state',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();
  $rows = array();
  foreach ($results as $node) {
  	      $title = '';
		  if(!user_access('edit guiding fund information')){
		  	  global $user;
			  $title = '没有上传记录';
			  if(user_access('upload apply file')){
				 $title = l('上传评审材料','applyfile/create/'. $node->id);
			  }
				 
			  $query = "SELECT id , name FROM " .
				           "{apply_file_info} where guiding_fund_id = ? and type = ? and user_id = ?";
			  $queryResult = db_query($query, array( $node->id, 1, $user->uid));
			  foreach ($queryResult as $template) {
				  if($template->id>0)
					  {  	
						$title = l($template->name,'applyfile/list/'.$template->id);	
					  }
			 }
		  }  
		  else{
		  	$title = l('查看评审材料','applyfile/guidingfund/'. $node->id);
		  }
		  if(user_access('edit guiding fund information')){
			  $rows[] = array(
		      'data' => array(
		        l($node->name, 'guidingfund/list/'. $node->id),
		        $node->principal_name,
		        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
		        $title,
		        l('名单设置', 'guidingfund/togradedlist_perpage/'.$node->id),
		      )
		      );
		  }
		  else{
		  	/* $companys = array();
		  	 $query = "SELECT allow_apply_list FROM " .
		           "{guiding_fund_info} where id = ?";
			  $company_list = db_query($query, array($node->id));	
			  foreach ($company_list as $company) {
			      $companys = explode(',',$company->allow_apply_list);
			  }*/
			 //if(in_array($user->uid,$companys, TRUE)&&$companys!=NULL){
			 if($node->state == 1) {
			  	 $rows[] = array(
			      'data' => array(
			        l($node->name, 'guidingfund/list/'. $node->id),
			        $node->principal_name,
			        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
			        $title,
			      )
			      );
			 }
		    }
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function guidingfund_expertset_page() {
 $html = '';
 if(user_access('edit guiding fund information')){
 	$html .= l('创建基金','guidingfund/create') . '<br />'. '<br />'; 
 }
 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '专家选择'),
      array('data' => '评审意见查看'),
      array('data' => '进入尽调企业名单管理'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
	  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        l('专家选择', 'expertmanage/choose/'.$node->id),
	        l('评审意见详情', 'expertmanage/all_graded_fund_view/'. $node->id),
	        l('进入尽调名单管理', 'guidingfund/toinvelist_page/'.$node->id),
	      )
	  );
  }
  
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function guidingfund_expertchoose_page() {
 $html = '';
 if(user_access('edit guiding fund information')){
 	$html .= l('创建基金','guidingfund/create') . '<br />'. '<br />'; 
 }
 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '电话', 'field' => 'phone'),
      array('data' => '邮箱', 'field' => 'mail'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '专家选择', 'field' => 'expert_choose'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'phone',
      'mail',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
	  $title = l('专家选择', 'expertmanage/choose/'.$node->id);
	  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        $node->phone,
	        $node->mail,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      )
	  );
  }
  
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}
//基金对应托管银行设置
function guidingfund_custodian_bankchoose_page() {
 $html = '';
 $html .= l('入库托管银行信息列表','custodian_bank_info/list').'<br><br>';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '已选择托管银行', 'field' => 'banks'),
      array('data' => '托管银行设置', 'field' => 'custodian_bank_choose'),
      array('data' => '资料提交管理', 'field' => 'custodian_bank_choose'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'custodian_bank_list',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  	  $banks = '';
	  $custodian_banks = array();
	  $custodian_banks = explode(',',$node->custodian_bank_list);
	  foreach ($custodian_banks as $bank) {
		  $query = "SELECT id,bank_name FROM " .
           "{custodian_bank_info} where id = ?";
  		  $queryResult = db_query($query, array($bank));
		  foreach ($queryResult as $result) {
			  $banks.=l($result->bank_name,'custodian_bank_info/list/'.$result->id).'&nbsp;&nbsp;';
		  }
	  }
	  $title = l('托管银行选择', 'custodian_bank_info/choose/'.$node->id);
	  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $banks,
	        $title,
	        l('资料提交管理', 'custodian_bank/guidingfund/'.$node->id),
	      )
	  );
  }
  
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function guidingfund_totanpanlist_page($fund_id) {
  drupal_set_title('进入合作谈判名单设置管理');
  $page_content = '';
  $page_content .= l('返回基金列表','lishihuijuece/list') . '<br />'. '<br />';
 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$page_content .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $render_array = array(
  		'#markup' => $page_content,
  );
  $form = drupal_get_form('guidingfund_totanpanlist_form', $fund_id);
  $render_array['#markup'] .= drupal_render($form ); 
  
  return $render_array; 
}

function guidingfund_totanpanlist_form($form, &$form_state, $perid){
  $query = "SELECT to_hezuotanpan_list FROM " .
           "{guiding_fund_info} where id = ?";
  $company_list = db_query($query, array($perid));	
  $companys = array();
  foreach ($company_list as $company) {
      $companys = explode(',',$company->to_hezuotanpan_list);
  }
  $query = "SELECT id ,name,user_id,apply_name,url,state FROM " .
           "{apply_file_info} where guiding_fund_id = ? and type = ?";
  $queryResult = db_query($query,  array($perid,1));	
  
  $header = array(
    'apply_name' => t('申请人'),
    'url' => t('申请文档下载'),
    'state' => t('审批状态'),
    'choose' => t('进入合作谈判(空表示未进入)'),
  );
  $options = array();
  foreach ($queryResult as $node) {
  	$state = '';
  	if(in_array($node->id,$companys, TRUE)&&$companys!=NULL){
  		$state=  '已选择';
  	}
    $options[$node->id] =array(
      'apply_name' => l($node->apply_name, 'applyfile/list/'. $node->id),
      'url' => l($node->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$node->url), 
      'state' => $node->state,
      'choose' => $state,   
    );
  }
  $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('没有申请记录'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  return $form;  
}

function guidingfund_totanpanlist_form_submit($form, &$form_state){
	 $values = NULL;
	 $values = $form_state['values'];		
	 $company_list = '';
	 foreach ($values['table'] as $rows) {
         $company_list.=$rows.',';
     }
	  db_update('guiding_fund_info')
  		->fields(array(
   			 'to_hezuotanpan_list' => $company_list,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'guidingfund/totanpanlist_page/'.$values['bid'];	 
}

function guidingfund_toinvelist_page($fund_id) {
  drupal_set_title('名单设置管理');
  $page_content = '';
  $page_content .= l('返回基金列表','guidingfund/guidingfund_expertset_page') . '<br />'. '<br />';
 $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$page_content .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $render_array = array(
  		'#markup' => $page_content,
  );
  $form = drupal_get_form('guidingfund_toinvelist_form', $fund_id);
  $render_array['#markup'] .= drupal_render($form ); 
  
  return $render_array; 
}

function guidingfund_toinvelist_form($form, &$form_state, $perid){
  $query = "SELECT to_investigate_list FROM " .
           "{guiding_fund_info} where id = ?";
  $company_list = db_query($query, array($perid));	
  $companys = array();
  foreach ($company_list as $company) {
      $companys = explode(',',$company->to_investigate_list);
  }
  $query = "SELECT id ,name,user_id,apply_name,url,state FROM " .
           "{apply_file_info} where guiding_fund_id = ? and type = ?";
  $queryResult = db_query($query,  array($perid,1));	
  
  $header = array(
    'apply_name' => t('申请人'),
    'url' => t('申请文档下载'),
    'state' => t('审批状态'),
    'choose' => t('进入尽职调查(空表示未进入)'),
  );
  $options = array();
  foreach ($queryResult as $node) {
  	$state = '';
  	if(in_array($node->id,$companys, TRUE)&&$companys!=NULL){
  		$state=  '已选择';
  	}
    $options[$node->id] =array(
      'apply_name' => l($node->apply_name, 'applyfile/list/'. $node->id),
      'url' => l($node->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$node->url), 
      'state' => $node->state,
      'choose' => $state,   
    );
  }
  $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('没有申请记录'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  return $form;  
}

function guidingfund_toinvelist_form_submit($form, &$form_state){
	 $values = NULL;
	 $values = $form_state['values'];		
	 $company_list = '';
	 foreach ($values['table'] as $rows) {
         $company_list.=$rows.',';
     }
	  db_update('guiding_fund_info')
  		->fields(array(
   			 'to_investigate_list' => $company_list,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'guidingfund/toinvelist_page/'.$values['bid'];	
	 
}

//过会企业名单设置
function guidingfund_finallist_page($perid) {
  drupal_set_title('过会企业名单设置管理');
  $page_content = '';
  $page_content .= l('返回基金列表','guidingfund/enterprise_announce_page') . '<br />'. '<br />';

  //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $render_array = array(
  		'#markup' => $page_content,
  );
  $form = drupal_get_form('guidingfund_finallist_form', $perid);
  $render_array['#markup'] .= drupal_render($form ); 
  
  return $render_array; 
}

function guidingfund_finallist_form($form, &$form_state, $perid){
  $query = "SELECT final_pass_list, to_investigate_list FROM " .
           "{guiding_fund_info} where id = ?";
  $company_list = db_query($query, array($perid));	
  $companys = array();
  $inve_companys = array();
  foreach ($company_list as $company) {
      $companys = explode(',',$company->final_pass_list);
	  $inve_companys = explode(',',$company->to_investigate_list);
  }
  $query = "SELECT id ,name,user_id,apply_name,url,state FROM " .
           "{apply_file_info} where guiding_fund_id = ? and type = ?";
  $queryResult = db_query($query,  array($perid,1));	
  
  $header = array(
    'apply_name' => t('申请人'),
    'url' => t('申请文档下载'),
    'state' => t('审批状态'),
    'choose' => t('过会企业名单(空表示未进入)'),
  );
  $options = array();
  foreach ($queryResult as $node) {
  	if(in_array($node->id,$inve_companys, TRUE)&&$inve_companys!=NULL){	
	  	$state = '';
	  	if(in_array($node->id,$companys, TRUE)&&$companys!=NULL){
	  		$state=  '已选择';
	  	}
	    $options[$node->id] =array(
	      'apply_name' => l($node->apply_name, 'applyfile/list/'. $node->id),
	      'url' => l($node->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$node->url), 
	      'state' => $node->state,
	      'choose' => $state,   
	    );
	}
  }
  $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('没有申请记录'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  return $form;  
}

function guidingfund_finallist_form_submit($form, &$form_state){
	 $values = NULL;
	 $values = $form_state['values'];		
	 $company_list = '';
	 foreach ($values['table'] as $rows) {
         $company_list.=$rows.',';
     }
	  db_update('guiding_fund_info')
  		->fields(array(
   			 'final_pass_list' => $company_list,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'guidingfund/toinvelist_page/'.$values['bid'];	
	 
}


function guidingfund_investigationset_page() {
 $html = '';

  $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '尽职调查机构选择'),
      array('data' => '尽调模板及结果材料'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        l('尽调机构选择', 'investigatedepartment/choose/'.$node->id),
	        l('尽调材料详情', 'investigate_file/guidingfund/'.$node->id),
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}
//尽调机构选择
function guidingfund_investigationchoose_page() {
 $html = '';
 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '电话', 'field' => 'phone'),
      array('data' => '邮箱', 'field' => 'mail'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '尽职调查机构选择', 'field' => 'investigatedepartment_choose'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'phone',
      'mail',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('尽调机构选择', 'investigatedepartment/choose/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        $node->phone,
	        $node->mail,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}
//尽调结果
function guidingfund_investigationresult_page() {
 $html = ''; 
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '尽职调查结果', 'field' => 'inve_result'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('尽调结果','investigate_file/guidingfund/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

///////
//提交进入专家审批名单
///////
function guidingfund_togradedlist_page() {
 $html = '';
 $header = array(
      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
      array('data' => '负责人', 'field' => 'principal_name'),
      array('data' => '电话', 'field' => 'phone'),
      array('data' => '邮箱', 'field' => 'mail'),
      array('data' => '成立时间', 'field' => 'timestamp'),
      array('data' => '提交进入专家评审名单', 'field' => 'guidingfund_togradedlist_choose'),
      );
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'phone',
      'mail',
      'timestamp',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
          $title = l('名单设置', 'guidingfund/togradedlist_perpage/'.$node->id);
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        $node->phone,
	        $node->mail,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      )
	      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function guidingfund_togradedlist_perpage($fund_id) {
  drupal_set_title('名单设置管理');
  $page_content = '';
  $page_content .= l('返回基金列表','guidingfund/guidingfund_togradedlist_page') . '<br />'. '<br />';

  $query = "SELECT id, name FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($fund_id));
  foreach($queryResult as $result){
  	$page_content .= '当前基金：' . '&nbsp;&nbsp;'. $result->name.'<br><br>';
  }
  //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
  $render_array = array(
  		'#markup' => $page_content,
  );
  $form = drupal_get_form('guidingfund_togradedlist_perform', $fund_id);
  $render_array['#markup'] .= drupal_render($form ); 
  
  return $render_array; 
}

function guidingfund_togradedlist_perform($form, &$form_state, $perid){
  $query = "SELECT to_graded_list FROM " .
           "{guiding_fund_info} where id = ?";
  $company_list = db_query($query, array($perid));	
  $companys = array();
  foreach ($company_list as $company) {
      $companys = explode(',',$company->to_graded_list);
  }
  $query = "SELECT id ,name,user_id,apply_name,url,state FROM " .
           "{apply_file_info} where guiding_fund_id = ? and type = ?";
  $queryResult = db_query($query,  array($perid,1));	
  
  $header = array(
    'apply_name' => t('申请人'),
    'url' => t('申请文档下载'),
    'state' => t('审批状态'),
    'choose' => t('提交专家评审(空表示未进入)'),
  );
  $options = array();
  foreach ($queryResult as $node) {
  	$state = '';
  	if(in_array($node->id,$companys, TRUE)&&$companys!=NULL){
  		$state=  '已选择';
  	}
    $options[$node->id] =array(
      'apply_name' => l($node->apply_name, 'applyfile/list/'. $node->id),
      'url' => l($node->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$node->url), 
      'state' => $node->state,
      'choose' => $state,   
    );
  }
  $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
  $form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#empty' => t('没有申请记录'),
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('提交'),
  );
  return $form;  
}

function guidingfund_togradedlist_perform_submit($form, &$form_state){
	 $values = NULL;
	 $values = $form_state['values'];		
	 $company_list = '';
	 foreach ($values['table'] as $rows) {
         $company_list.=$rows.',';
     }
	  db_update('guiding_fund_info')
  		->fields(array(
   			 'to_graded_list' => $company_list,
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'guidingfund/togradedlist_perpage/'.$values['bid'];	
	 
}

function guidingfund_enterprise_announce_page() {
 $html = '';
 if(user_access('edit guiding fund information')){
 	$html .= l('创建基金','guidingfund/create') . '<br />'. '<br />'; 
 }
 if(user_access('edit guiding fund information')){
	 $header = array(
	      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
	      array('data' => '负责人', 'field' => 'principal_name'),
	      array('data' => '成立时间', 'field' => 'timestamp'),
	      array('data' => '提交过会企业名单'),
	      array('data' => '过会企业公示'),
	      );
 }
 else{
	 $header = array(
	      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
	      array('data' => '负责人', 'field' => 'principal_name'),
	      array('data' => '成立时间', 'field' => 'timestamp'),
	      array('data' => '过会企业公示'),
	      );
 }
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      'enterprise_announce_id',
      ));
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  	
	  $title = '没有发布过会企业公示';
	  if($node->enterprise_announce_id>0){
	  	 $query = "SELECT id, title FROM " .
           "{enterprise_announce} where id = ?";
         $queryResult = db_query($query, array($node->enterprise_announce_id));
		  $ifempty = TRUE;
		 foreach ($queryResult as $announce) {
		 	 $ifempty = FALSE;
		    if($announce->id > 0)		
		 		$title = l($announce->title, 'enterprise_announce/list/'.$announce->id);
		    else{
		    	if(user_access('edit guiding fund information')){
		    		$title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
				}
		    }
		 }	 
		 if($ifempty){
		 	if(user_access('edit guiding fund information')){
		    		$title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
				}
		 }
	  }  
	  else{
	  	if(user_access('edit guiding fund information')){
		    		$title = l('创建过会企业公示', 'enterprise_announce/publish/'. $node->id);
		}
	  }
	 if(user_access('edit guiding fund information')){
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        l('名单设置', 'guidingfund/finallist_page/'.$node->id),
	        $title,
	      )
	      );
	 }
	 else{
	 	 $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $title,
	      )
	      );
	 }
	  
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function guidingfund_list_perpage($perid) {
  // content variable that will be returned for display
  $page_content = '';
  global $user;
  $page_content .= l('返回基金列表','guidingfund/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  if(user_access('edit guiding fund information')){
 	$page_content .= l('编辑','guidingfund/edit/'.$perid) . '<br />'. '<br />'; 
 }
  
  $query = "SELECT name,principal_name,phone,mail,timestamp,remark,announce_id, enterprise_announce_id,apply_file_url,state FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  
  $links= '';
  foreach ($queryResult as $links ) {
  $state_key =  $links->state;
  $state_array = fund_state_dropdown_options();
  $current_state = $state_array[$state_key];
  $page_content .= '<h4><B>基金当前所在阶段:'. '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$current_state.'</B></h4><br>';
 if(user_access('edit guiding fund information')){
	 $header = array(
	      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
	      array('data' => '负责人', 'field' => 'principal_name'),
	      array('data' => '成立时间', 'field' => 'timestamp'),
	      array('data' => '联系电话', 'field' => 'phone'),
	      array('data' => '邮箱地址', 'field' => 'mail'),
	      //array('data' => '提交过会企业名单'),
	      array('data' => '征集公告', 'field' => 'announce'),
	      );
 }
 else{
	 $header = array(
	      array('data' => '基金名称', 'field' => 'name', 'sort' => 'desc'),
	      array('data' => '负责人', 'field' => 'principal_name'),
	      array('data' => '成立时间', 'field' => 'timestamp'),
	      array('data' => '联系电话', 'field' => 'phone'),
	      array('data' => '邮箱地址', 'field' => 'mail'),
	      array('data' => '征集公告'),
	      );
 }
  $query = db_select('guiding_fund_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(15)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'principal_name',
      'timestamp',
      'phone',
      'mail',
      'announce_id',
      ))
	  ->condition('id',$perid,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  	
	  $title = '没有发布征集公告';
	  if($node->announce_id>0){
	  	 $query = "SELECT id, title FROM " .
           "{announce} where id = ?";
         $queryResult = db_query($query, array($node->announce_id));
		  $ifempty = TRUE;
		 foreach ($queryResult as $announce) {
		 	 $ifempty = FALSE;
		    if($announce->id > 0)		
		 		$title = l($announce->title, 'announce/list/'.$announce->id);
		    else{
		    	if(user_access('edit guiding fund information')){
		    		$title = l('创建征集公告', 'announce/publish/'. $node->id);
				}
		    }
		 }	 
		 if($ifempty){
		 	if(user_access('edit guiding fund information')){
		    		$title = l('创建征集公告', 'announce/publish/'. $node->id);
				}
		 }
	  }  
	  else{
	  	if(user_access('edit guiding fund information')){
		    		$title = l('创建征集公告', 'announce/publish/'. $node->id);
		}
	  }
	 if(user_access('edit guiding fund information')){
		  $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $node->phone,
	        $node->mail,
	        //l('名单设置', 'guidingfund/finallist_page/'.$node->id),
	        $title,
	      )
	      );
	 }
	 else{
	 	 $rows[] = array(
	      'data' => array(
	        l($node->name, 'guidingfund/list/'. $node->id),
	        $node->principal_name,
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $node->phone,
	        $node->mail,
	        $title,
	      )
	      );
	 }
	  
  }
  $page_content .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有基金信息',//Optional empty text for the table if resultset is empty
      )
      );
  $page_content .= theme('pager',
      array(
            'tags' => array()
      )
      );
	//////
	//申报材料模板
	//////
	 $ifnonemodlefile = '没有上传记录';
	 if(user_access('edit guiding fund information')){
	 	$ifnonemodlefile = l('上传评审材料模板','applyfile/create/'.$perid);
	 }
	 
	 $header = array(
      array('data' => '已上传申报材料模板', 'field' => 'name',),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      );
	  $query = db_select('apply_file_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(5)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'url',
	      'timestamp',
	      'remark',
	      ))
		  ->condition('guiding_fund_id',$perid,'=')
		  ->condition('type',0,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {
	      $rows[] = array(
	      'data' => array(
	        l($node->name, 'applyfile/list/'. $node->id),
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $node->remark,
	      )
	      );
	  }
	  $page_content .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => $ifnonemodlefile,//Optional empty text for the table if resultset is empty
	      )
	      );
	//////
	//评审材料
	//////
	if(user_access('edit guiding fund information')){
		$page_content .= l('查看已上传评审材料','applyfile/guidingfund/'.$perid) . '<br />'. '<br />'; 
	}
	
	if(user_access('upload apply file')&&!user_access('edit guiding fund information')){
	  $header = array(
	      array('data' => '已上传申报材料', 'field' => 'name',),
	      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
	      array('data' => '备注', 'field' => 'remark'),
	      array('data' => '反馈意见', 'field' => 'reply_remark'),
	      );
	  $query = db_select('apply_file_info', 'n')
	      ->extend('PagerDefault') //Pager Extender
	      ->limit(5)//10 results per page
	      ->extend('TableSort')//Sorting Extender
	      ->orderByHeader($header)//Field to sort on is picked from $header
	      ->fields ('n', array (
	      'id',
	      'name',
	      'url',
	      'timestamp',
	      'remark',
	      'reply_id',
	      ))
		  ->condition('guiding_fund_id',$perid,'=')
		  ->condition('type',1,'=')
		  ->condition('user_id',$user->uid,'=');
	  $results = $query
	      ->execute();
	
	  $rows = array();
	  foreach ($results as $node) {
	  	  if($node->remark == '')
		  	$node->remark = "无备注";
		  $reply_remark = '无反馈意见';
		  $query = "SELECT id, reply_remark FROM " .
           "{reply_file_info} where id = ?";
	  	  $replyResult = db_query($query, array($node->reply_id));
		  foreach ($replyResult as $reply) {
		  	if($reply->id>0){
		  		$reply_remark = $reply->reply_remark; 
		  	}
		  }
	      $rows[] = array(
	      'data' => array(
	        l($node->name, 'applyfile/list/'. $node->id),
	        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
	        $node->remark,
	        $reply_remark,
	      )
	      );
	  }
	  $page_content .= theme('table', 
	      array(
	            'header' => $header,
	            'rows'=>$rows,
	            //'caption' => '反馈意见列表',//Optional Caption for the table
	            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
	            'empty' => l('上传评审材料','applyfile/create/'.$perid),//Optional empty text for the table if resultset is empty
	      )
	      );
    }
	
	if($links->enterprise_announce_id>0){
		$query = "SELECT id, title FROM " .
          	 "{enterprise_announce} where id = ?";
         $queryResult = db_query($query, array($links->enterprise_announce_id));
		 $ifempty = TRUE;
		 foreach ($queryResult as $announce) {
		 	$ifempty = FALSE;
		 	if($announce->id>0)	{
				if(user_access('edit guiding fund information')){
			 	  $page_content .= '<h5>过会企业公示：'.l($announce->title, 'enterprise_announce/edit/'. $links->enterprise_announce_id).'</h5><br />';	  
				}
				else{
					$page_content .= '<h5>过会企业公示：'.l($announce->title, 'enterprise_announce/list/'. $links->enterprise_announce_id).'</h5><br />';	  
				}
			}
		    else{
				if(user_access('edit guiding fund information')){
				 	$page_content .= l('创建过会企业公示','enterprise_announce/publish/'.$perid) . '<br />'. '<br />'; 
				 }
			}	
		 }
		 if($ifempty){
		 	if(user_access('edit guiding fund information')){
				 	$page_content .= l('创建过会企业公示','enterprise_announce/publish/'.$perid) . '<br />'. '<br />'; 
			}
		 }
	  }	
	else{
			if(user_access('edit guiding fund information')){
				 	$page_content .= l('创建过会企业公示','enterprise_announce/publish/'.$perid) . '<br />'. '<br />'; 
				}
		}	
  }
  
	  // More coming....
	  if ($links == '') {
	    $page_content .= "没有该基金信息.";
	  }

  return $page_content;
}

function guidingfund_edit_page($perid) {
  $page_content = '';
  if(user_access('view experts information'))
  	$page_content .= l('返回基金列表','guidingfund/list') . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
  $page_content .= l('浏览','guidingfund/list/'.$perid) . '<br />'. '<br />'; 
  drupal_set_title('基金信息管理');
	 
	 $query = "SELECT id FROM " .
           "{guiding_fund_info} where id = ?";
 	 $queryResult = db_query($query, array($perid));
	 $ifempty =TRUE;
	  foreach ($queryResult as $links ) {
	  	if($links->id>0)
		  	$ifempty = FALSE;
	  }
	 if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('guidingfund_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
	 else{
	 	 $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('guidingfund_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function fund_state_dropdown_options() {
    return array(
        '0' => '公告发布',
        '1' => '申报',
        '2' => '专家评审',        
        '3' => '尽职调查',
        '4' => '理事会决策',
        '5' => '合作谈判',
        '6' => '过会企业公示',        
        '7' => '投后管理',
        '8' => '基金退出',
    );
}

function guidingfund_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT name,principal_name,phone,mail,timestamp,remark,state FROM " .
           "{guiding_fund_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $principal_name = '';
  $phone = '';
  $mail = ''; 
  $datetime = '';
  $remark = '';
  $current_state = 0;
  foreach ($queryResult as $links ) {
  	$name = $links->name;
    $principal_name = $links->principal_name;
	$phone = $links->phone;
    $mail = $links->mail;
	$datetime = getdate($links->timestamp);
	$remark = $links->remark;
	$current_state = $links->state;
  }
   $options = fund_state_dropdown_options();
   $value_state= isset($form_state['guidingfund_edit_form']['state']) ? $form_state['guidingfund_edit_form']['state'] : $current_state ;
   
   $form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   $form['name'] = array(
	  '#title' => t('基金名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guidingfund_edit_form']['name'])?$_SESSION['guidingfund_edit_form']['name']:$name,
	 );
	 
	 $form['principal_name'] = array(
	  '#title' => t('负责人名称'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guidingfund_edit_form']['principal_name'])?$_SESSION['guidingfund_edit_form']['principal_name']:$principal_name,
	 );
	 
	 $form['phone'] = array(
	  '#title' => t('联系电话'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guidingfund_edit_form']['phone'])?$_SESSION['guidingfund_edit_form']['phone']:$phone,
	 );
	 
	  $form['mail'] = array(
	  '#title' => t('联系邮箱'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['guidingfund_edit_form']['mail'])?$_SESSION['guidingfund_edit_form']['mail']:$mail,
	 );
	 
      $form['timestamp'] = array(
	     '#type' => 'date', // types 'date_popup', 'date_text' and 'date_timezone' are also supported. See .inc file.
	     '#title' => t('成立时间'),
	     '#default_value' => isset($_SESSION['guidingfund_edit_form']['timestamp'])?$_SESSION['guidingfund_edit_form']['timestamp']:
	     	array('year' =>  $datetime['year'], 'month' =>  $datetime['mon'], 'day' => $datetime['mday']), 
	  );
	  
	  $form['state'] = array(
        '#type' => 'select',
        '#title' => '基金当前所在阶段',
        '#options' => $options,
        '#default_value' => $value_state,
     );
	 
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['guidingfund_edit_form']['remark'])?$_SESSION['guidingfund_edit_form']['remark']:$remark,
	 );
	
	  $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该基金'),
	    '#submit' => array('guidingfund_edit_form_deleate'),
	  );
  return $form;
}

function guidingfund_edit_form_submit($form, &$form_state){
	  $values = NULL;
	  $values = $form_state['values'];		
	  $datetime = mktime(0, 0, 0,$values['timestamp']['month'], $values['timestamp']['day'], $values['timestamp']['year']);
	  db_update('guiding_fund_info')
  		->fields(array(
   			 'principal_name' => $values['principal_name'],
   			 'name' => $values['name'],
   			 'phone' => $values['phone'],
   			 'mail' => $values['mail'],
   			 'timestamp' =>  $datetime,
   			 'remark' =>  $values['remark'],
   			 'state' => $values['state'],
  			))
  		->condition('id', $values['bid'])
  		->execute();
	 $form_state['redirect'] = 'guidingfund/edit/'.$values['bid'];
}

function guidingfund_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['guidingfund_edit_form'] = $form_state['values'];
	 $values = $_SESSION['guidingfund_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'guidingfund/deleate/'.$values['bid'];
}

function guidingfund_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后所以与该基金相关的信息将不可恢复！';
  
  drupal_set_title('删除基金信息');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('guidingfund_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function guidingfund_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('guidingfund_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function guidingfund_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['guidingfund_edit_form'])){
		  	$form_state['redirect'] = 'guidingfund/list';
	  }else{
		  $values = $_SESSION['guidingfund_edit_form'];
		  unset($_SESSION['guidingfund_edit_form']);
		  $form_state['redirect'] = 'guidingfund/edit/'.$values['bid'];
	  }
}

function guidingfund_deleate_form_submit($form, &$form_state){
 if(empty($_SESSION['guidingfund_edit_form'])){
		  	$form_state['redirect'] = 'guidingfund/list';
	  }else{
		  $values = $_SESSION['guidingfund_edit_form'];
		  unset($_SESSION['guidingfund_edit_form']);
		  db_delete('guiding_fund_info')
			->condition('id' ,$values['bid'])
			->execute();
		  db_delete('fund_exit_info')
			->condition('fund_id' ,$values['bid'])
			->execute();
		  $form_state['redirect'] = 'guidingfund/list';

	  }

}

/////////
//申报材料管理
////////

function applyfile_create_page($perid){
	 drupal_set_title('申报材料提交');
	
	 $render_array = array(
	   		'#markup' => '',
     );
	 
     $form = drupal_get_form('applyfile_create_form',$perid);
	 $render_array['#markup'] .= drupal_render($form);
	 
	 return $render_array;
}

function applyfile_create_form($form, &$form_state, $perid){
	 $form['bid'] = array('#type' => 'hidden', '#value' => $perid);	 
	 $form['tips'] = array(
	  '#prefix' =>'<div id="tips">',
	  '#markup' => t('<span class="form-required">*</span> 号为必填项。'),
	  '#suffix' =>'</div>',
	 );
	 
	 $form['upload'] = array(
	'#type' => 'managed_file',
	'#title' => '申报材料',
	'#required' => TRUE,
	'#upload_location' => 'public://my_uploads',
	'#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	if(!user_access('edit guiding fund information')){
	 $form['apply_name'] = array(
	  '#title' => t('申报人：'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>"",
	 );	 
	}
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>"",
	 );
	 	  	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('确认'),
	 );
	  return $form;
}

function applyfile_create_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  
	$saveurl = file_uri_target($file->uri);
	$fid = $file->fid;
	global $user; 
	if ($file != null) {   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
			$type = 1;
			$query = "SELECT id, name FROM " .
		           "{guiding_fund_info} where id = ? ";
		    $queryResult = db_query($query, array($values['bid'] ));
			$fundname = '';
			
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$fundname = $links->name;
				}
			}
			$apply_name = '';
			if(user_access('edit guiding fund information')){
			 	$type=0;
				$filename .= $fundname."_申报材料模板";
			}  
			else{
				$query = "SELECT  name FROM " .
		           "{users} where uid = ? ";
		   		$queryResult = db_query($query, array($user->uid));
				foreach ($queryResult as $username ) {
					$filename .= $username->name."_申报材料";
				}
				$apply_name = $values['apply_name'];
			}
			$query = "SELECT id,file_managed_id FROM " .
		           "{apply_file_info} where user_id = ? and guiding_fund_id = ?";
		    $file_managed_id = '';  //已上传申报材料在file_managed表中对应的id
		    $queryResult = db_query($query, array($user->uid, $values['bid'] ));
			$uploadid = 0; //已上传申报材料id
			foreach ($queryResult as $links ) {
				if($links->id>0){
					$file_managed_id = $links->file_managed_id;
					$uploadid = $links->id;
				}
			}
			if($uploadid==0){
				$last_id = db_insert('apply_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'apply_name' => $apply_name,
			   			 'remark' => $values['remark'],
			   			 'guiding_fund_id' => $values['bid'],
			   			 'user_id' => $user->uid,
			   			 'type' => $type,
			   			 'file_managed_id' => $fid,
			   			 'state' => "未审批",
			  			))->execute();
				  if ($last_id!=NULL) {
				     db_update('guiding_fund_info')
				  		->fields(array(
				   			 'apply_file_url' => $saveurl,	 
				  			))
				  		->condition('id',$values['bid'])
				  		->execute();
					 $form_state['redirect'] = 'guidingfund/list/'.$values['bid'];
					 	    
				  } else {
				    
				    // 数据写入失败了
				    drupal_set_message('抱歉，遇到问题，提交失败了', 'error');
				    
				  }
			}
			else{
				if($file_managed_id>0){
					$file = file_load($file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
					db_delete('file_managed')
				    ->condition('fid',$file_managed_id)
					->execute();
				}	
				db_update('apply_file_info')
			  		->fields(array(
			   			 'name' => $filename,
			   			 'url' => $saveurl,
			   			 'timestamp' => $_SERVER['REQUEST_TIME'],
			   			 'remark' => $values['remark'],
			   			 'guiding_fund_id' => $values['bid'],
			   			 'type' => $type,
			   			 'file_managed_id' => $fid,
			   			 'state' => "未审批",
			  			))
			  		->condition('id',$uploadid)
			  		->execute();
				db_update('guiding_fund_info')
			  		->fields(array(
			   			 'apply_file_url' => $saveurl,	 
			  			))
			  		->condition('id',$values['bid'])
			  		->execute();
				$form_state['redirect'] = 'guidingfund/list/'.$values['bid'];
			}
			
		} 
		else {
		form_set_error('upload',$extension_errors[0]); 
		}
	}
}

function applyfile_list_perpage($perid) {
  // content variable that will be returned for display
  $page_content = '';
  
  global $user;
  $query = "SELECT id, name,url,timestamp,remark, guiding_fund_id,user_id,type,apply_name,state,reply_id FROM " .
           "{apply_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  foreach ($queryResult as $links ) {
  	if($links->user_id != $user->uid &&$links->type != 0) {
  		if(!user_access('edit guiding fund information')){
  			$query = "SELECT id, name,url,timestamp,remark, guiding_fund_id,user_id,type,apply_name,state,reply_id FROM " .
           		"{apply_file_info} where user_id = ?";
			$queryResult = db_query($query, array($user->uid));
			foreach ($queryResult as $insidelinks ) {
				$links = $insidelinks;
			}
  		}
  	}
	 $reply_remark = '';
		  $query = "SELECT id, reply_remark FROM " .
           "{reply_file_info} where id = ?";
	  	  $replyResult = db_query($query, array($links->reply_id));
		  foreach ($replyResult as $reply) {
		  	if($reply->id>0){
		  		$reply_remark = $reply->reply_remark; 
		  	}
		  }
   $page_content .= l('返回基金列表','guidingfund/list/'.$links->guiding_fund_id) . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
   if($links->type != 1 && user_access('edit guiding fund information')){
 		$page_content .= l('编辑','applyfile/edit/'.$perid)  . '<br />'. '<br />'; 
 	}
   else if($links->type == 1 && $links->user_id == $user->uid)
   {
  	 	$page_content .= l('切换成编辑模式','applyfile/edit/'.$perid)  . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
   }
   else if($links->type == 1 && user_access('edit guiding fund information'))
   {
  	 	$page_content .= l('切换成审批模式','applyfile/reply/'.$perid)  . '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; 
   }
   
	if($links->type == 0) {
    	$page_content .= '<h5>申报材料模板下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
		$page_content .= '<h5>上传时间:</h5>'. format_date($links->timestamp, 'custom', 'D, Y-m-d').'<br />'.'<br />';
    	$page_content .= '<h5>备注: </h5>'.$links->remark.'<br />'.'<br />';
    }	
	else if($links->type == 1) {
		$query = "SELECT id FROM " .
           "{rukurongzi} where user_id = ?";
	   $info_id = '';
	   $replyResult = db_query($query, array($links->user_id));
			  foreach ($replyResult as $reply) {
			  	if($reply->id>0){
			  		$info_id = $reply->id; 
			  	}
			  }

  		$page_content .= l('申报企业信息','enterprise_information/view/'.$info_id) . '<br />'. '<br />';
		$page_content .= '<h5>申报材料下载:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
		$page_content .= '<h5>申报人:</h5>'.$links->apply_name.'<br />'.'<br />';
		$page_content .= '<h5>上传时间: </h5>'. format_date($links->timestamp, 'custom', 'D, Y-m-d').'<br />'.'<br />';
    	$page_content .= '<h5>备注:</h5>'.$links->remark.'<br />'.'<br />';
		 $header = array(
	      array('data' => '已反馈材料', 'field' => 'name'),
	      array('data' => '反馈时间', 'field' => 'timestamp', 'sort' => 'desc'),
	      array('data' => '审批状态', 'field' => 'state'),
	      array('data' => '反馈意见', 'field' => 'reply_remark'),
	      );
		  $query = db_select('reply_file_info', 'n')
		      ->extend('PagerDefault') //Pager Extender
		      ->limit(10)//10 results per page
		      ->extend('TableSort')//Sorting Extender
		      ->orderByHeader($header)//Field to sort on is picked from $header
		      ->fields ('n', array (
		      'id',
		      'name',
		      'url',
		      'timestamp',
		      ))
			  ->condition('relay_to_id',$perid,'=');
		  $results = $query
		      ->execute();
		
		  $rows = array();
		  foreach ($results as $node) {
		  	 $reply_remark = '';
		  $query = "SELECT id, reply_remark FROM " .
           "{reply_file_info} where id = ?";
	  	  $replyResult = db_query($query, array($links->reply_id));
		  foreach ($replyResult as $reply) {
		  	if($reply->id>0){
		  		$reply_remark = $reply->reply_remark; 
		  	}
		  }
		      $rows[] = array(
		      'data' => array(
		        l($node->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$node->url),
		        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
		       	$links->state,
		        $reply_remark,
		      )
		      );
		  }
		  $page_content .= theme('table', 
		      array(
		            'header' => $header,
		            'rows'=>$rows,
		            //'caption' => '反馈意见列表',//Optional Caption for the table
		            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
		            'empty' => '无反馈意见',//Optional empty text for the table if resultset is empty
		      )
		      );
		  $page_content .= theme('pager',
		      array(
		            'tags' => array()
		      )
		      );
    	
    }
  }
  // More coming....
  if ($page_content == '') {
    $page_content = "没有该上传申报材料信息.";
  }

  return $page_content;
}

function applyfile_guidingfund_page($perid) {
  // content variable that will be returned for display
  $html = '';
  $html .= l('查看基金信息','guidingfund/list/'.$perid) . '<br />'. '<br />';
  $header = array(
      array('data' => '已上传申报材料模板', 'field' => 'name',),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      );
  $query = db_select('apply_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      ))
	  ->condition('guiding_fund_id',$perid,'=')
	  ->condition('type',0,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
      $rows[] = array(
      'data' => array(
        l($node->name, 'applyfile/list/'. $node->id),
        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
        $node->remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
	  
  $header = array(
      array('data' => '已上传申报材料', 'field' => 'name'),
      array('data' => '申报人', 'field' => 'apply_name'),
      array('data' => '上传时间', 'field' => 'timestamp', 'sort' => 'desc'),
      array('data' => '备注', 'field' => 'remark'),
      array('data' => '审批状态', 'field' => 'state'),
      array('data' => '反馈意见', 'field' => 'reply_remark'),
      );
  $query = db_select('apply_file_info', 'n')
      ->extend('PagerDefault') //Pager Extender
      ->limit(10)//10 results per page
      ->extend('TableSort')//Sorting Extender
      ->orderByHeader($header)//Field to sort on is picked from $header
      ->fields ('n', array (
      'id',
      'name',
      'url',
      'timestamp',
      'remark',
      'user_id',
      'apply_name',
      'state',
      'reply_id',
      ))
	  ->condition('guiding_fund_id',$perid,'=')
	  ->condition('type',1,'=');
  $results = $query
      ->execute();

  $rows = array();
  foreach ($results as $node) {
  	  $reply_remark = '';
	  $query = "SELECT id, reply_remark FROM " .
           "{reply_file_info} where id = ?";
  	  $replyResult = db_query($query, array($node->reply_id));
	  foreach ($replyResult as $reply) {
	  	if($reply->id>0){
	  		$reply_remark = $reply->reply_remark; 
	  	}
	  }
      $rows[] = array(
      'data' => array(
        l($node->name, 'applyfile/list/'. $node->id),
        $node->apply_name,
        format_date($node->timestamp, 'custom', 'D, Y-m-d'),
        $node->remark,
        $node->state,
        $reply_remark,
      )
      );
  }
  $html .= theme('table', 
      array(
            'header' => $header,
            'rows'=>$rows,
            //'caption' => '反馈意见列表',//Optional Caption for the table
            'sticky' => TRUE,//Optional to indicate whether the table headers should be sticky
            'empty' => '没有上传记录',//Optional empty text for the table if resultset is empty
      )
      );
  $html .= theme('pager',
      array(
            'tags' => array()
      )
      );
  return ($html); 
}

function applyfile_edit_perpage($perid) {
  $page_content = '';
  $page_content .= l('查看基金信息','guidingfund/list/') . '<br />'. '<br />';
  $page_content .= l('切换成浏览模式','applyfile/list/'.$perid) . '<br />'. '<br />'; 	
  drupal_set_title('申报材料管理');
	 
  $query = "SELECT id,name, url FROM " .
           "{apply_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  foreach ($queryResult as $links ) {
	  if($links->id>0)
		  $ifempty = FALSE;
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	 
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 $form = drupal_get_form('applyfile_create_form');
		 $render_array['#markup'] .= drupal_render($form);
	 }
 else{
	 	 $page_content .= '<h5>已提交申报材料:</h5>'.l($links->name, 'http://' .$_SERVER['HTTP_HOST'].'/drupal/sites/default/files/'.$links->url).'<br />'.'<br />';
	     $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		$form = drupal_get_form('applyfile_edit_form',$perid);
  		$render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function applyfile_edit_form($form, &$form_state, $perid){
  
  $query = "SELECT id, name,url,remark, guiding_fund_id,user_id,type,reply_id,apply_name,state,file_managed_id FROM " .
           "{apply_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
 
  $name = '';
  $url = '';
  $remark = ''; 
  $reply_remark = '';
  $guiding_fund_id = '';
  $type = '';
  $reply_id = '';
  $apply_name = '';
  $state = '';
  global $user;
 foreach ($queryResult as $links ) {
  	if($links->user_id != $user->uid){
  		if(!user_access('edit guiding fund information')){
  			$query = "SELECT id, name,url,remark, guiding_fund_id,user_id,type,reply_id,apply_name,state,file_managed_id FROM " .
           		"{apply_file_info} where user_id = ?";
			$queryResult = db_query($query, array($user->uid));
			foreach ($queryResult as $insidelinks ) {
				$links = $insidelinks;
			}
  		}
  	}
	$query = "SELECT id, reply_remark FROM " .
           "{reply_file_info} where id = ?";
  	  $replyResult = db_query($query, array($links->reply_id));
	  foreach ($replyResult as $reply) {
	  	if($reply->id>0){
	  		$reply_remark = $reply->reply_remark; 
	  	}
	  }
	$name =  $links->name;
	$url =  $links->url;
    $remark =  $links->remark;
	$guiding_fund_id =  $links->guiding_fund_id;
	$type =  $links->type;
	$reply_id = $links->reply_id;
  	$apply_name = $links->apply_name;
  	$state = $links->state;
	$file_managed_id = $links->file_managed_id;
  }
   if($type == 1){
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
   	$form['type'] = array('#type' => 'hidden', '#value' => $type);
	$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
	$form['guiding_fund_id'] = array('#type' => 'hidden', '#value' => $guiding_fund_id);
	
	$form['name'] = array(
	  '#title' => t('文件名'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['applyfile_edit_form']['name'])?$_SESSION['applyfile_edit_form']['name']:$name,
	 );
	 
    $form['apply_name'] = array(
	  '#title' => t('申报人'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['applyfile_edit_form']['apply_name'])?$_SESSION['applyfile_edit_form']['apply_name']:$apply_name,
	 );
	 
	 $form['upload'] = array(
	  '#type' => 'managed_file',
	  '#title' => '重新提交申报材料',
	  '#required' => FAlSE,
	  '#upload_location' => 'public://my_uploads',
	  '#upload_validators' => array(
	    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
		'file_validate_size' => array(20*1024*1024)),
	);
	
	 $form['remark'] = array(
	  '#title' => t('备注'),
	  '#type' => 'textarea',
	  '#required' => FALSE,
	  '#default_value' =>isset($_SESSION['applyfile_edit_form']['remark'])?$_SESSION['applyfile_edit_form']['remark']:$remark,
	 );
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交修改'),
	  );
	 //表单元素“提交”按钮
	  $form['deleate'] = array(
	    '#type' => 'submit',
	    '#value' => t('删除该申报'),
	    '#submit' => array('applyfile_edit_form_deleate'),
	  );
   }	
	else if($type == 0){
	   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	   	$form['type'] = array('#type' => 'hidden', '#value' => $type);
		$form['file_managed_id'] = array('#type' => 'hidden', '#value' => $file_managed_id);
		$form['guiding_fund_id'] = array('#type' => 'hidden', '#value' => $guiding_fund_id);
		
		$form['name'] = array(
		  '#title' => t('文件名'),
		  '#type' => 'textfield',
		  '#required' => TRUE,
		  '#default_value' =>isset($_SESSION['applyfile_edit_form']['name'])?$_SESSION['applyfile_edit_form']['name']:$name,
		 );
		 
		 $form['upload'] = array(
		  '#type' => 'managed_file',
		  '#title' => '重新提交申报材料模板',
		  '#required' => FAlSE,
		  '#upload_location' => 'public://my_uploads',
		  '#upload_validators' => array(
		    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
			'file_validate_size' => array(20*1024*1024)),
		);
		
		 $form['remark'] = array(
		  '#title' => t('备注'),
		  '#type' => 'textarea',
		  '#required' => FALSE,
		  '#default_value' =>isset($_SESSION['applyfile_edit_form']['remark'])?$_SESSION['applyfile_edit_form']['remark']:$remark,
		 );
		 
		 $form['submit'] = array(
		    '#type' => 'submit',
		    '#value' => t('提交修改'),
		  );
		 //表单元素“提交”按钮
		  $form['deleate'] = array(
		    '#type' => 'submit',
		    '#value' => t('删除该模板'),
		    '#submit' => array('applyfile_edit_form_deleate'),
		  );
   	  }
	  
  return $form;
}

function applyfile_edit_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  

	
	global $user; 
	$filetype = $values['type'];
	$filename = $values['name'];
	$filemanagedid = $values['file_managed_id'];
	$uploadid = $values['bid'];
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
								
			if($filemanagedid>0){
				$file = file_load($filemanagedid);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
				  ->condition('fid',$filemanagedid)
				  ->execute();
			}	
			if($filetype == 1){
				db_update('apply_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'file_managed_id' => $fid,
			   	    'apply_name' => $values['apply_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
			}
			else  if($filetype == 0){
				db_update('apply_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'url' => $saveurl,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'file_managed_id' => $fid,
			  		))
			  		->condition('id',$uploadid)
			  		->execute();
				db_update('guiding_fund_info')
			  		->fields(array(
			   			 'apply_file_url' => $saveurl,	 
			  			))
			  		->condition('id',$values[guiding_fund_id])
			  		->execute();				
			}			
			$form_state['redirect'] = 'applyfile/list/'.$values['bid'];
		}			
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
			if($filetype == 1){
				db_update('apply_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			   	    'apply_name' => $values['apply_name'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();				
			}
			else  if($filetype == 0){
				db_update('apply_file_info')
			  	 ->fields(array(
			   		'name' => $filename,
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'remark' => $values['remark'],
			  		))
			  		->condition('id',$uploadid)
			  		->execute();			
			}			
			$form_state['redirect'] = 'applyfile/list/'.$values['bid'];
	}
}

function applyfile_edit_form_deleate($form, &$form_state){
	 $values = NULL;
	 $_SESSION['applyfile_edit_form'] = $form_state['values'];
	 $values = $_SESSION['applyfile_edit_form'] ;
	 //表单重定向到确认页面
	 $form_state['redirect'] = 'applyfile/deleate/'.$values['bid'];
}

function applyfile_deleate_page($perid) {
  // content variable that will be returned for display
  $page_content = '删除后申报内容将不可恢复！';
  
  drupal_set_title('删除申报内容');
	 
	 $render_array = array(
	   '#markup' => $page_content,
	 );
	 
	 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
	 $form = drupal_get_form('applyfile_deleate_form');
	 $render_array['#markup'] .= drupal_render($form);
	 
	 //Drupal7的页面回调，返回的应该是一个数组
  return $render_array;

}

function applyfile_deleate_form($form, &$form_state){
 //表单元素“返回”按钮
  $form['back'] = array(
    '#type' => 'submit',
    '#value' => t('取消'),
    '#submit' => array('applyfile_deleate_form_back'),
  );
 //表单元素“提交”按钮
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('删除'),
  );
  
  return $form;
}

function applyfile_deleate_form_back($form, &$form_state){
	if(empty($_SESSION['applyfile_edit_form'])){
		  	$form_state['redirect'] = 'applyfile/list';
	  }else{
		  $values = $_SESSION['applyfile_edit_form'];
		  unset($_SESSION['applyfile_edit_form']);
		  $form_state['redirect'] = 'applyfile/edit/'.$values['bid'];
	  }
}

function applyfile_deleate_form_submit($form, &$form_state){
 if(empty($_SESSION['applyfile_edit_form'])){
		  	$form_state['redirect'] = 'guidingfund/list';
	  }else{
		  $values = $_SESSION['applyfile_edit_form'];
		  unset($_SESSION['applyfile_edit_form']);
		  if($values['type'] == 0)
		  {

		  }
		  else if($values['type'] == 1){
		  	db_update('guiding_fund_info')
			  	->fields(array(
			   			 'apply_file_url' => '',	 
			  			))
			  	->condition('id',$values[guiding_fund_id])
			  	->execute();
		  	
		  }
		  else if($values['type'] == 2){
		  	
		  }
		  $file = file_load($values['file_managed_id']);
				  if($file!=NULL){
					 file_delete($file);
				  }
		  db_delete('file_managed')
				  ->condition('fid',$values['file_managed_id'])
				  ->execute();
		  db_delete('apply_file_info')
			->condition('id' ,$values['bid'])
			->execute();
			
		  $form_state['redirect'] = 'guidingfund/list';

	  }

}

function applyfile_reply_perpage($perid) {
  $page_content = '';
  $page_content .= l('查看基金列表','guidingfund/list/') . '<br />'. '<br />';	
  drupal_set_title('申报材料审批'); 
  $state = '';
  $query = "SELECT id, name, url, type,state FROM " .
           "{apply_file_info} where id = ?";
  $queryResult = db_query($query, array($perid));
  $ifempty =TRUE;
  $links = '';
  foreach ($queryResult as $links ) {
	  if($links->id>0){
	  	 $state = $links->state;
	  	 $ifempty = FALSE;
		 if($links->type == 0){
		 	drupal_goto('applyfile/list/'.$perid);
		 }
	  }  
  }
  if($ifempty)
	 {
	 	 $render_array = array(
	   		'#markup' => '',
		 );
	     drupal_goto('guidingfund/list/');
		 //该页面的正文为一个表单，注意对于表单，这里需要使用drupal_render呈现一下。
		 //$form = drupal_get_form('applyfile_create_form');
		 //$render_array['#markup'] .= drupal_render($form);
	 }
 else{
 	    $query = "SELECT id FROM " .
           "{reply_file_info} where relay_to_id = ?";
    	$queryResult = db_query($query, array($perid));
		foreach ($queryResult as $links ) {
		   if($links->id>0){
		   	  $page_content .= l('切换成浏览模式','applyfile/list/'.$perid) . '<br />'. '<br />'; 
		   }
		}

	 	 $render_array = array(
	   		'#markup' => $page_content,
		 );
	 
		 $form = drupal_get_form('applyfile_reply_form',$perid, $state);
  		 $render_array['#markup'] .= drupal_render($form);
	 }	 
	 //Drupal7的页面回调，返回的应该是一个数组
	 return $render_array;
}

function applyfile_reply_form($form, &$form_state, $perid, $state){
    $query = "SELECT id, reply_remark FROM " .
           "{reply_file_info} where relay_to_id = ?";
    $queryResult = db_query($query, array($perid));
	$reply_remark = '';
	$reply_id = '';
	foreach ($queryResult as $links ) {
		if($links->id>0){
			$reply_id = $links->id;
			$reply_remark = $links->reply_remark;
		}
	}		
   	$form['bid'] = array('#type' => 'hidden', '#value' => $perid);
	 
    $form['state'] = array(
	  '#title' => t('审批状态'),
	  '#type' => 'textfield',
	  '#required' => TRUE,
	  '#default_value' =>isset($_SESSION['applyfile_edit_form']['apply_name'])?$_SESSION['applyfile_edit_form']['apply_name']:$state,
	 );
	 if($reply_id>0){
	 	 $form['upload'] = array(
		  '#type' => 'managed_file',
		  '#title' => '重新提交审批回复材料',
		  '#required' => FAlSE,
		  '#upload_location' => 'public://my_uploads',
		  '#upload_validators' => array(
		    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
			'file_validate_size' => array(20*1024*1024)),
		);
	 }
	 else{
	 	 $form['upload'] = array(
		  '#type' => 'managed_file',
		  '#title' => '提交审批回复材料',
		  '#required' => FAlSE,
		  '#upload_location' => 'public://my_uploads',
		  '#upload_validators' => array(
		    'file_validate_extensions' => array('doc xls pdf docx xlsx'),
			'file_validate_size' => array(20*1024*1024)),
		);
	 }	
	 $form['reply_remark'] = array(
	  '#title' => t('审批意见'),
	  '#type' => 'textarea',
	  '#required' => TRUE,
	  '#default_value' =>$reply_remark,
	 );
	 
	 $form['submit'] = array(
	    '#type' => 'submit',
	    '#value' => t('提交审批'),
	  );	
	
  return $form;
}

function applyfile_reply_form_submit($form, &$form_state){
	$values=$form_state['values'];	
	$fid = $form_state['values']['upload']; 
	$filename = '';
	$file = file_load($fid);  	
	global $user; 
	$replyid='';
    $query = "SELECT id, file_managed_id FROM " .
           "{reply_file_info} where relay_to_id = ?";
    $queryResult = db_query($query, array($values['bid']));
	foreach ($queryResult as $links ) {
		if($links->id>0){
			$replyid = $links->id;
	        if($links->file_managed_id>0){
	        	 $file = file_load($links->file_managed_id);
				  if($file!=NULL){
					 file_delete($file);
				  }
				db_delete('file_managed')
					->condition('fid',$links->file_managed_id)
					->execute();			
			}
		}
	}	
	if ($file != null) {
		$saveurl = file_uri_target($file->uri);
		$fid = $file->fid;   
		//$extension_errors=file_validate_extensions($file, "jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp docx");   
	    $extension_errors=file_validate_extensions($file, "doc xls pdf docx xlsx");   
		if (!$extension_errors) {  
			$file->status = FILE_STATUS_PERMANENT;   
			file_save($file);
           if($replyid>0){
			db_update('reply_file_info')
			  ->fields(array(
			   	'name' => '反馈回复文件',
		   		'url' => $saveurl,
		   		'reply_remark' => $values['reply_remark'],
		   		'timestamp' =>  $_SERVER['REQUEST_TIME'],
		   		'file_managed_id' =>  $fid,
			  	))
			  ->condition('id',$replyid)
			  ->execute();		
			db_update('apply_file_info')
					  ->fields(array(
					   	'state' => $values['state'],
					  	))
					  ->condition('id',$values['bid'])
					  ->execute();
				
		   }	        
		   else {
				$last_id = db_insert('reply_file_info')
		  		->fields(array(
		   			 'name' => '反馈回复文件',
		   			 'url' => $saveurl,
		   			 'reply_remark' => $values['reply_remark'],
		   			 'timestamp' =>  $_SERVER['REQUEST_TIME'],
		   			 'file_managed_id' =>  $fid,
		   			 'relay_to_id' => $values['bid'],
		  			))->execute();
					
				if($last_id>0){
					db_update('apply_file_info')
					  ->fields(array(
					   	'reply_id' => $last_id,
					   	'state' => $values['state'],
					  	))
					  ->condition('id',$values['bid'])
					  ->execute();
				}
		   }
		}		
		else {
			form_set_error('upload',$extension_errors[0]); 
		}
	}
	else{
		if($replyid>0){
			db_update('reply_file_info')
			  	->fields(array(
			   		'timestamp' => $_SERVER['REQUEST_TIME'],
			   	    'reply_remark' => $values['reply_remark'],
			  	))
			  	->condition('id',$replyid)
			  	->execute();	
			db_update('apply_file_info')
					  ->fields(array(
					   	'state' => $values['state'],
					  	))
					  ->condition('id',$values['bid'])
					  ->execute();			
		}		
		else {
			$last_id = db_insert('reply_file_info')
		  		->fields(array(
		   			 'reply_remark' => $values['reply_remark'],
		   			 'timestamp' =>  $_SERVER['REQUEST_TIME'],
		   			 'relay_to_id' => $values['bid'],
		  			))->execute();
					
				if($last_id>0){
					db_update('apply_file_info')
					  ->fields(array(
					   	'reply_id' => $last_id,
					   	'state' => $values['state'],
					  	))
					  ->condition('id',$values['bid'])
					  ->execute();
				}
		}
	}
	$form_state['redirect'] = 'applyfile/list/'.$values['bid'];	
}


